// pages/userConsole/userConsole.js
import Toast from '../../dist/toast/toast';
const db = wx.cloud.database()

Page({
  data: {
    userAvatar: '',
    userName: '',
    show: false,
    shows: false,
    fileList: [],
    folder: 'opinion',
    imgurllistL: [],
    opinionmessage: '',
    contactmessage: '',
    loading: false,
    currentYear: new Date().getFullYear(),
    // 记账提醒相关数据
    reminderEnabled: false,
    reminderTime: '20:00',
    showReminderDialog: false,
    showTimePicker: false
  },

  onLoad: function (options) {
    this.getUserInfo();
    this.getReminderSettings();
  },

  onShow: function() {
    this.getUserInfo();
    this.getReminderSettings();
  },

  getUserInfo() {
    const avatar = wx.getStorageSync('avatar');
    const name = wx.getStorageSync('name');
    
    if (avatar && name) {
      this.setData({
        userAvatar: avatar,
        userName: name
      });
      Toast(`欢迎 ${name}`);
    } else {
      // 如果本地存储没有用户信息，跳转到登录页
      wx.redirectTo({
        url: '../signin/signin'
      });
    }
  },

  // 获取提醒设置
  getReminderSettings() {
    const userId = wx.getStorageSync('id');
    if (!userId) return;

    db.collection('test').doc(userId).get().then(res => {
      if (res.data) {
        this.setData({
          reminderEnabled: res.data.reminderEnabled || false,
          reminderTime: res.data.reminderTime || '20:00'
        });
      }
    }).catch(err => {
      console.error('获取提醒设置失败：', err);
    });
  },

  // 打开提醒设置弹窗
  toggleReminder() {
    this.setData({
      showReminderDialog: true
    });
  },

  // 关闭提醒设置弹窗
  closeReminderDialog() {
    this.setData({
      showReminderDialog: false
    });
  },

  // 开关提醒状态改变
  onReminderSwitchChange(event) {
    this.setData({
      reminderEnabled: event.detail
    });
  },

  // 显示时间选择器
  showTimePicker() {
    this.setData({
      showTimePicker: true
    });
  },

  // 关闭时间选择器
  closeTimePicker() {
    this.setData({
      showTimePicker: false
    });
  },

  // 确认时间选择
  onTimeConfirm(event) {
    this.setData({
      reminderTime: event.detail,
      showTimePicker: false
    });
  },

  // 保存提醒设置
  saveReminderSettings() {
    const userId = wx.getStorageSync('id');
    if (!userId) {
      Toast('请先登录');
      return;
    }

    wx.showLoading({
      title: '保存中...',
    });

    db.collection('test').doc(userId).update({
      data: {
        reminderEnabled: this.data.reminderEnabled,
        reminderTime: this.data.reminderTime
      }
    }).then(() => {
      wx.hideLoading();
      Toast.success('设置已保存');
      this.setData({
        showReminderDialog: false
      });

      // 设置提醒
      if (this.data.reminderEnabled) {
        this.setReminder();
      } else {
        this.cancelReminder();
      }
    }).catch(err => {
      wx.hideLoading();
      console.error('保存提醒设置失败：', err);
      Toast.fail('保存失败，请重试');
    });
  },

  // 设置提醒
  setReminder() {
    const [hours, minutes] = this.data.reminderTime.split(':');
    wx.requestSubscribeMessage({
      tmplIds: ['YOUR_TEMPLATE_ID'], // 需要替换为您的模板消息ID
      success: (res) => {
        if (res['YOUR_TEMPLATE_ID'] === 'accept') {
          Toast.success('提醒设置成功');
        }
      },
      fail: (err) => {
        console.error('订阅消息失败：', err);
        Toast.fail('提醒设置失败');
      }
    });
  },

  // 取消提醒
  cancelReminder() {
    // 可以在这里添加取消提醒的逻辑
    Toast('提醒已关闭');
  },

  wuquan() {
    Toast('暂无权限哦！');
  },

  toindex() {
    // 清除本地存储的用户信息
    wx.removeStorageSync('avatar');
    wx.removeStorageSync('name');
    wx.removeStorageSync('id');
    
    wx.redirectTo({
      url: '../signin/signin'
    });
  },

  about() {
    this.setData({
      show: true
    });
  },

  opinion() {
    this.setData({
      shows: true
    });
  },

  onClose() {
    this.setData({
      shows: false
    });
  },

  opinionmessages(e) {
    this.setData({
      opinionmessage: e.detail
    });
  },

  contactmessages(e) {
    this.setData({
      contactmessage: e.detail
    });
  },

  afterRead(event) {
    const { file } = event.detail;
    const { fileList = [] } = this.data;
    fileList.push({ ...file, status: 'uploading', message: '上传中' });
    this.setData({ fileList });
  },

  uploadToCloud() {
    wx.cloud.init();
    const { fileList } = this.data;
    if (!fileList.length) {
      wx.showToast({ title: '请选择图片', icon: 'none' });
    } else {
      const uploadTasks = fileList.map((file, index) => this.uploadFilePromise(`my-photo${index}.png`, file));
      Promise.all(uploadTasks)
        .then(data => {
          wx.showToast({ title: '上传成功', icon: 'none' });
          const newFileList = data.map(item => ({ url: item.fileID }));
          this.setData({ cloudPath: data, fileList: newFileList });
        })
        .catch(e => {
          wx.showToast({ title: '上传失败', icon: 'none' });
          console.log(e);
        });
    }
  },

  uploadFilePromise(fileName, chooseResult) {
    return wx.cloud.uploadFile({
      cloudPath: fileName,
      filePath: chooseResult.url
    });
  },

  deleteimg(e) {
    this.setData({
      fileList: []
    })
  },

  commitdata() {
    let that = this

    if (!this.data.opinionmessage) {
      wx.showToast({ title: '请填写意见!', icon: 'none' });
    } else {
      this.setData({
        loading: true
      })
      that.uploadToCloud()
      setTimeout(() => {
        let postdata = {
          opinion: that.data.opinionmessage,
          contact: that.data.contactmessage,
          imgurl: that.data.fileList
        }
        db.collection('opinion').add({
          data: postdata
        }).then(res => {
          Toast.success('提交成功！');
          that.setData({
            opinionmessage: '',
            contactmessage: '',
            fileList: [],
            loading: false,
            shows:false
          })
        })
      }, 1500)
    }
  }
})